package com.koocloud.electroplatemanage.service.impl;

import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koocloud.electroplatemanage.auth.mapper.UserMapper;
import com.koocloud.electroplatemanage.common.pojo.ResponseTemplate;
import com.koocloud.electroplatemanage.mapper.IncomePartJudgeMapper;
import com.koocloud.electroplatemanage.mapper.MainProductionMapper;
import com.koocloud.electroplatemanage.mapper.ProductPlanUrgentMapper;
import com.koocloud.electroplatemanage.mapper.ProductionPlanMapper;
import com.koocloud.electroplatemanage.pojo.AssignJobVo;
import com.koocloud.electroplatemanage.pojo.BtProductPlanUrgent;
import com.koocloud.electroplatemanage.pojo.IncomePartJudgeVo;
import com.koocloud.electroplatemanage.pojo.ProductionPlan;
import com.koocloud.electroplatemanage.pojo.mainpojo.WIP;
import com.koocloud.electroplatemanage.service.ProductPlanUrgentService;
import com.koocloud.electroplatemanage.utils.HexUtil;
import com.koocloud.electroplatemanage.utils.ListUtil;
import com.koocloud.electroplatemanage.utils.SecondCheck;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.koocloud.electroplatemanage.constant.MainWIPRouteConstant.SCHEDULING;

/**
 * @program: Information_platform
 * @description: 生产计划加急表实现层
 * @author: 2019110501
 * @create: 2020-11-04 10:21
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class ProductPlanUrgentServiceImpl implements ProductPlanUrgentService {

    @Resource
    private ProductPlanUrgentMapper productPlanUrgentMapper;//生产计划加急

    @Resource
    private ProductionPlanMapper productionPlanMapper;//生产计划

    @Resource
    private IncomePartJudgeMapper IncomePartJudgeMapper;//主表
    @Resource
    private MainProductionMapper mainProductionMapper;
    Lock lock = new ReentrantLock();

    //新增 加急表 成功时，将主表的数据状态置为1（0删除1.未删除2.加急状态），设置生产计划的状态为0  order 从1开始递增
    @Override
    public ResponseTemplate insert(BtProductPlanUrgent btProductPlanUrgent) {
            try {
                lock.lock();
                //获取目前的order
                String large_class="生产计划";
                String sub_class="生产计划加急";
                String productPlanUrgentOrder = HexUtil.getProductPlanUrgentOrder(large_class, sub_class);
                btProductPlanUrgent.setOrder(productPlanUrgentOrder);
                btProductPlanUrgent.setCreateTime(HexUtil.getCurrentDateForString());
                btProductPlanUrgent.setDeleteFlag("1");
                //插入生产计划加急表
               Integer num = productPlanUrgentMapper.insert(btProductPlanUrgent);

               //设置生产计划的状态为0
                String id= btProductPlanUrgent.getProductionPlanId();
                log("传过来的生产计划的id："+id);
                String deleteFlag="0";

                int delete = productionPlanMapper.delete(id, deleteFlag);

                //将主表的数据状态置为1（0删除1.未删除2.加急状态）
                //根据id获取对应的关联主表的id
                String incomepartjudgeId= productionPlanMapper.selectIncomepartjudgeIdById(id);

                //根据主表id将状态置为1
               Integer number = IncomePartJudgeMapper.productionPlanDelete(id);

                if (num>0 && delete>0 && number >0) {
                    return ResponseTemplate.builder().code(0).message("插入生产计划加急成功").count(0l).build();
                } else {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return ResponseTemplate.builder().code(1).message("插入生产计划加急失败").count(0l).build();
                }
            } catch(Exception e){
                //出现异常返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }finally {
                lock.unlock();
            }
    }

    /**
     *生产计划加急列表的全查询
     * @param page
     * @param limit
     * @return
     */
    @Override
    public ResponseTemplate selectAllData(String page, String limit) {
        //校验分页参数是否为纯数字 并且page和limit不都等于0
        if(Validator.isNumber(page)&&Validator.isNumber(limit)&&!("0".equals(page)&&"0".equals(limit))) {
            try {
                lock.lock();
                int rows = -1;
                //开始查询在工表，状态为4的插入生产计划(排产)
                List<WIP> wipList= mainProductionMapper.selectAllWIPByLocation(SCHEDULING);
                if(!StringUtils.isEmpty(wipList)) {
                    for(WIP wip:wipList) {
                        //获取工单号
                        if(!StringUtils.isEmpty(wip.getWorkOrderNumber())) {
                            //数据库重复工单号校验
                            int count = productionPlanMapper.selectWorkOrderNumberCount(wip.getWorkOrderNumber());
                            if(count>0) {
                                continue;
                            }


                            ProductionPlan insertProductionPlan = new ProductionPlan();

                            if(!StringUtils.isEmpty(wip.getEntryPerson())) {
                                //设置创建人
                                insertProductionPlan.setCreator(wip.getEntryPerson());
                            }
                            if(!StringUtils.isEmpty(wip.getEntryTime())) {
                                //设置创建时间
                                insertProductionPlan.setCreateTime(wip.getEntryTime());
                            }
                            if(!StringUtils.isEmpty(wip.getLine())) {
                                //设置线路
                                insertProductionPlan.setLine(wip.getLine());
                            }
                            String workOrderNumber = wip.getWorkOrderNumber();
                            //设置工单号
                            insertProductionPlan.setWorkOrderNumber(workOrderNumber);
                            //设置删除标志
                            insertProductionPlan.setDeleteFlag("1");
                            if(!"A".equals(workOrderNumber.substring(workOrderNumber.length()-1,workOrderNumber.length()))) {
                                continue;
                            }
                            //根据工单号查询台账表记录
                            IncomePartJudgeVo incomePartJudgeVo = IncomePartJudgeMapper.selectByWorkOrderNumber(workOrderNumber);





                            if(!StringUtils.isEmpty(incomePartJudgeVo)) {
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getOrderNumber())) {
                                    //设置订单号
                                    insertProductionPlan.setOrderNumber(incomePartJudgeVo.getOrderNumber());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getIncomePartUnitCode())) {
                                    //设置来件单位编码
                                    insertProductionPlan.setIncomePartUnitCode(incomePartJudgeVo.getIncomePartUnitCode());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getIncomePartTime())) {
                                    //设置来件时间
                                    insertProductionPlan.setIncomePartTime(incomePartJudgeVo.getIncomePartTime());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getIncomePartQuantity())) {
                                    //设置来件数量
                                    insertProductionPlan.setIncomePartQuantity(incomePartJudgeVo.getIncomePartQuantity());
                                    //当前单据数量
                                    insertProductionPlan.setCurrentQuantity(incomePartJudgeVo.getIncomePartQuantity());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getIncomePartJudgeResult())) {
                                    //设置来件验收结果
                                    insertProductionPlan.setIncomePartJudgeResult(incomePartJudgeVo.getIncomePartJudgeResult());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getInspector())) {
                                    //设置检验员编码
                                    insertProductionPlan.setInspector(incomePartJudgeVo.getInspector());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getDegreeUrgency())) {
                                    //设置紧急程度
                                    insertProductionPlan.setDegreeUrgency(incomePartJudgeVo.getDegreeUrgency());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getDrawNoCode())) {
                                    //设置图号编码
                                    insertProductionPlan.setDrawNoCode(incomePartJudgeVo.getDrawNoCode());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getModelNumber())) {
                                    //设置型号
                                    insertProductionPlan.setModelNumber(incomePartJudgeVo.getModelNumber());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getModelType())) {
                                    //设置型别
                                    insertProductionPlan.setModelType(incomePartJudgeVo.getModelType());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getPartName())) {
                                    //设置零件名称
                                    insertProductionPlan.setPartName(incomePartJudgeVo.getPartName());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getTypeWorkCode())) {
                                    //设置工种编码
                                    insertProductionPlan.setTypeWorkCode(incomePartJudgeVo.getTypeWorkCode());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getDegreeUrgency())) {
                                    //设置生产计划删除标志
                                    insertProductionPlan.setDeleteFlag("0");
                                    BtProductPlanUrgent btProductPlanUrgent = new BtProductPlanUrgent();
                                    //设置加急生产计划工单号
                                    btProductPlanUrgent.setProductionPlanId(workOrderNumber);
                                    //获取目前的order
                                    String large_class="生产计划";
                                    String sub_class="生产计划加急";
                                    //获取排序号
                                    String productPlanUrgentOrder = HexUtil.getProductPlanUrgentOrder(large_class, sub_class);
                                    btProductPlanUrgent.setOrder(productPlanUrgentOrder);
                                    btProductPlanUrgent.setCreateTime(HexUtil.getCurrentDateForString());
                                    btProductPlanUrgent.setDeleteFlag("1");
                                    //插入生产计划加急表
                                    productPlanUrgentMapper.insert(btProductPlanUrgent);
                                }
                                rows=productionPlanMapper.insert(insertProductionPlan);
                                //记录成功插入条数
                            }

                        }
                    }
                }
                //在工表插入完成后开始查询
                if(StringUtils.isEmpty(wipList)||(wipList.size()>0&&rows>0)||(wipList.size()>=0&&rows==-1)) {
                //开始分页
                PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));

                //获取生产计划加急的全列表
                List<LinkedHashMap> productionPlanList = productPlanUrgentMapper.selectAllData();

                //构造分页实体
                PageInfo<LinkedHashMap> info=new PageInfo<>(productionPlanList);
                if (info.getTotal()>0) {
                    //查询到数据
                    return ResponseTemplate.builder().code(0).message("查询成功").count(info.getTotal()).data(info.getList()).build();
                } else {
                    //没有查询到数据
                    return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
                }

                }
                else {
                    return ResponseTemplate.builder().code(1).message("在工表数据导入失败").count(0l).build();
                }
            } catch (Exception e) {
                //遇到异常，返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }finally {
                lock.unlock();
            }
        }
        else {
            return ResponseTemplate.builder().code(1).message("分页参数错误").count(0l).build();
        }
    }

    /**
     * 修改加急单的order
     * @param urgentId
     * @param order
     * @return
     */
    @Override
    public ResponseTemplate update(String urgentId, String order) {
        try {
            lock.lock();
            //修改加急单的order
            int rows = productPlanUrgentMapper.update(urgentId,order);
            //将数据库中比当前order小的进行+1
            int num = productPlanUrgentMapper.updateOrder(order);
            String s = productPlanUrgentMapper.selectIdByUrgentId(urgentId);
            productionPlanMapper.expedited(s,"1");
            if(rows>0 && num >0) {
                return ResponseTemplate.builder().code(0).message("修改加急单的order成功").count(1l).build();
            }
            else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("修改加急单的order失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    /**
     * 二次加急
     * @param urgentId
     * @param order
     * @return
     */
    @Override
    public ResponseTemplate expedited(String urgentId, String order) {
        try {
            List<BtProductPlanUrgent> list = productPlanUrgentMapper.findExpedited();
            if (!list.isEmpty()){
                productPlanUrgentMapper.update(list.get(0).getUrgentId(),(Integer.parseInt(list.get(0).getOrder())-1000000000)+"");
                productionPlanMapper.mExpedited(list.get(0).getProductionPlanId(),"1");
            }
            int expedited = productPlanUrgentMapper.expedited(urgentId, order);
            if (expedited > 0) {
                //批量删除成功返回数据
                return ResponseTemplate.builder().code(0).message("二次加急成功").count((long)expedited).build();
            } else {
                //批量删除失败返回提示
                return ResponseTemplate.builder().code(1).message("二次加急失败").count(0l).build();
            }

        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }

    /**
     * 根据id查询加急单的order
     * @param urgentId
     * @return
     */
    @Override
    public ResponseTemplate selectOrderById(String urgentId) {
        try {
            //根据id查询加急单的order
            LinkedHashMap  linkedHashMap = productPlanUrgentMapper.selectOrderById(urgentId);
            if(!linkedHashMap.isEmpty()) {
                return ResponseTemplate.builder().code(0).message("根据id查询加急单的order成功").count(1l).build();
            }
            else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("根据id查询加急单的order失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }

    /**
     *
     * @param urgentId
     * @return
     */
    @Override
    public ResponseTemplate deleteExpedited(String urgentId) {
        try {
            //根据urgentId获取生产计划表id
            String id= productPlanUrgentMapper.selectIdByUrgentId(urgentId);
            //找到二次加急单
            List<BtProductPlanUrgent> expedited = productPlanUrgentMapper.findExpedited();
            int update = productPlanUrgentMapper.update(expedited.get(0).getUrgentId(), (Integer.parseInt(expedited.get(0).getOrder()) - 1000000000) + "");
            //将生产计划表标志修改为2
            String deleteFlag="2";
            Integer number = productionPlanMapper.cancelExpedited(id,deleteFlag);

            if(update>0 && number>0) {
                return ResponseTemplate.builder().code(0).message("取消二次加急单成功").count(1l).build();
            }
            else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("取消二次加急单失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }

    }
    /**
     * 物理删除加急单
     * @param urgentId
     * @return
     */
    @Override
    public ResponseTemplate delete(String urgentId) {
        try {
            lock.lock();
            //根据urgentId获取生产计划表id
            String id= productPlanUrgentMapper.selectIdByUrgentId(urgentId);
            //根据id物理删除加急单
            Integer num = productPlanUrgentMapper.delete(urgentId);


            //将生产计划表标志修改为1
            String deleteFlag="1";
            Integer number = productionPlanMapper.cancelDelete(id,deleteFlag);

            if(num>0 && number>0) {
                return ResponseTemplate.builder().code(0).message("取消加急单成功").count(1l).build();
            }
            else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("取消加急单失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    public  void log(String str){
        System.out.println("=================="+str+"============>");
    }
}
